package com.maybach.core.ao.impl;

import com.maybach.common.BizResult;
import com.maybach.common.VO.ApplyForLoanVO;
import com.maybach.common.VO.ContractVO;
import com.maybach.common.VO.LetterInfoVO;
import com.maybach.common.dto.LoanOrderDTO;
import com.maybach.common.enums.*;
import com.maybach.common.enums.order.*;
import com.maybach.common.model.*;
import com.maybach.common.query.*;
import com.maybach.core.ao.ActLogAO;
import com.maybach.core.ao.LoanOrderAO;
import com.maybach.core.ao.UserMsgAO;
import com.maybach.core.ao.facade.LoanOrderAOFacade;
import com.maybach.core.dubbo.consumer.adapter.B2BCarServiceDubboAdapter;
import com.maybach.core.enums.NumEnum;
import com.maybach.core.form.finance.FinanceDetailForm;
import com.maybach.core.form.order.*;
import com.maybach.core.generator.NumGenerator;
import com.maybach.core.manager.*;
import com.maybach.core.security.AdminUser;
import com.maybach.core.security.AdminUserUtil;
import com.maybach.dubbo.api.model.*;
import com.maybach.dubbo.api.query.LoanOrderQueryModel;
import com.maybach.util.ImgUrlUtil;
import com.maybach.util.PriceUtil;
import com.maybach.util.StringUtil;
import com.maybach.util.query.support.PageResult;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by houenxun on 16/2/23.
 */
@Component
public class LoanOrderAOImpl implements LoanOrderAO {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LoanOrderManager loanOrderManager;

    @Autowired
    private OrderManager orderManager;

    @Autowired
    private FinanceFlowManager financeFlowManager;

    @Autowired
    private OrderInfoManager orderInfoManager;

    @Autowired
    private ShippingOrderManager shippingOrderManager;

    @Autowired
    private ActLogManager actLogManager;

    @Autowired
    private LogisticsCompanyManager logisticsCompanyManager;

    @Autowired
    private CarFormalitiesManager carFormalitiesManager;
    @Autowired
    private UserMsgAO userMsgAO;

    @Autowired
    NumGenerator numGenerator;
    @Autowired
    UserManager userManager;
    @Autowired
    PartnerManager partnerManager;
    @Autowired
    B2BCarServiceDubboAdapter b2BCarServiceDubboAdapter;

    @Autowired
    CarSnapManager carSnapManager;
    @Autowired
    LoanOrderAOFacade loanOrderAOFacade;
    @Autowired
    ActLogAO actLogAO;

    @Override
    public void addLoanOrder(AddLoanOrderForm addLoanOrderForm) {
        UserDO userDO = userManager.selectByPrimaryKey(addLoanOrderForm.getBuyerId());
        PartnerDO partnerDO = null;
        if (null != userDO && userDO.getPartnerId() != null) {
            partnerDO = partnerManager.selectByPrimaryKey(userDO.getPartnerId());
        }

        OrderDO orderDO = this.assemblyOrder(addLoanOrderForm, partnerDO);

        orderManager.insertSelective(orderDO);
        LoanOrderDO loanOrderDO = this.assemblyLoanOrder(addLoanOrderForm, partnerDO);
        loanOrderDO.setOutOrderId(orderDO.getId());

        loanOrderManager.insertSelective(loanOrderDO);
        actLogAO.addLog(ActLogBizTypeEnum.LoanOrder, loanOrderDO.getId(), "创建订单宝", ActLogActorNameEnum.createLoanOrder);
    }


    @Override
    public com.maybach.dubbo.api.BizResult<LoanOrderCreateResultModel> addLoanOrder(CreateLoanOrderModel model) {
        com.maybach.dubbo.api.BizResult<LoanOrderCreateResultModel> result = new com.maybach.dubbo.api.BizResult<LoanOrderCreateResultModel>();
        UserDO userDO = userManager.selectByPrimaryKey(model.getUserId());
        if (null == userDO) {
            result.setMsg("用户不存在");
            logger.error("用户不存在[userId={}]", model.getUserId());
            return result;
        }
        PartnerDO partnerDO = null;
        if (null != userDO && userDO.getPartnerId() != null) {
            partnerDO = partnerManager.selectByPrimaryKey(userDO.getPartnerId());
        }
        if (null == partnerDO) {
            result.setMsg("用户未认证");
            logger.error("partner不存在[userId={}]", model.getUserId());
            return result;
        }


        OrderDO orderDO = this.assemblyOrder(model, partnerDO);

        orderManager.insertSelective(orderDO);
        LoanOrderDO loanOrderDO = this.assemblyLoanOrder(model, partnerDO);
        loanOrderDO.setOutOrderId(orderDO.getId());

        loanOrderManager.insertSelective(loanOrderDO);
        LoanOrderCreateResultModel resultModel = new LoanOrderCreateResultModel();
        resultModel.setOrderName(loanOrderDO.getOrderName());
        resultModel.setId(loanOrderDO.getId());
        resultModel.setGmtCreate(new Date());
        result.setResult(resultModel);
        return result;

    }


    private OrderDO assemblyOrder(CreateLoanOrderModel model, PartnerDO partnerDO) {
        OrderDO orderDO = new OrderDO();
        orderDO.setId(numGenerator.getLongNum(NumEnum.order));
        orderDO.setOrderNo(numGenerator.generate(NumEnum.order, orderDO.getId()));
        orderDO.setBuyerId(model.getUserId());
        orderDO.setDealerId(partnerDO.getId());
        orderDO.setDealerName(partnerDO.getCorpName());
        orderDO.setStatus(OrderStatusEnum.init.getCode());
        return orderDO;
    }


    private OrderDO assemblyOrder(AddLoanOrderForm addLoanOrderForm, PartnerDO partnerDO) {
        OrderDO orderDO = new OrderDO();
        orderDO.setId(numGenerator.getLongNum(NumEnum.order));
        orderDO.setOrderNo(numGenerator.generate(NumEnum.order, orderDO.getId()));
        orderDO.setBuyerId(addLoanOrderForm.getBuyerId());
        orderDO.setDealerId(partnerDO.getId());
        orderDO.setDealerName(partnerDO.getCorpName());
        orderDO.setStatus(OrderStatusEnum.init.getCode());
        return orderDO;
    }

    private LoanOrderDO assemblyLoanOrder(AddLoanOrderForm addLoanOrderForm, PartnerDO partnerDO) {
        LoanOrderDO loanOrderDO = new LoanOrderDO();
        loanOrderDO.setId(numGenerator.getLongNum(NumEnum.loanOrder));
        loanOrderDO.setOrderNo(numGenerator.generate(NumEnum.loanOrder, loanOrderDO.getId()));
        loanOrderDO.setBuyerId(addLoanOrderForm.getBuyerId());
        loanOrderDO.setDealerId(partnerDO.getId());
        loanOrderDO.setDealerName(partnerDO.getCorpName());
        loanOrderDO.setManager(addLoanOrderForm.getManager());
        loanOrderDO.setOrderName(addLoanOrderForm.getOrderName());
        loanOrderDO.setStatus(LoanOrderStatusEnum.init.getCode());

        return loanOrderDO;
    }

    private LoanOrderDO assemblyLoanOrder(CreateLoanOrderModel model, PartnerDO partnerDO) {
        LoanOrderDO loanOrderDO = new LoanOrderDO();
        loanOrderDO.setId(numGenerator.getLongNum(NumEnum.loanOrder));
        loanOrderDO.setOrderNo(numGenerator.generate(NumEnum.loanOrder, loanOrderDO.getId()));
        loanOrderDO.setBuyerId(model.getUserId());
        loanOrderDO.setDealerId(partnerDO.getId());
        loanOrderDO.setDealerName(partnerDO.getCorpName());
        loanOrderDO.setStatus(LoanOrderStatusEnum.init.getCode());

        loanOrderDO.setOrderName(model.getOrderName());

        return loanOrderDO;
    }

    @Override
    public void editLoanOrder(EditLoanOrderForm editLoanOrderForm) {
        // 当数据为空的时候,进行添加操作
        CarSnapDO carSnapDO = carSnapManager.selectByLoanOrderId(editLoanOrderForm.getId());
        OrderInfoQuery query = new OrderInfoQuery();
        query.createCriteria().andBizIdEqualTo(editLoanOrderForm.getId());
        List<OrderInfoDO> list = orderInfoManager.selectByQuery(query);

        if (carSnapDO == null) {
            insertOrUpdateEditDO(list, editLoanOrderForm, carSnapDO);
        } else {
            insertOrUpdateEditDO(list, editLoanOrderForm, carSnapDO);
        }

        loanOrderAOFacade.insertLog(ActLogBizTypeEnum.LoanOrder.name(), editLoanOrderForm.getId(),
                "更新 订单宝ID = " + editLoanOrderForm.getId(),
                ActLogActorNameEnum.updateOrder.name());
    }

    @Override
    public void editLoanOrderFinanceDetail(FinanceDetailForm financeDetailForm) {
        LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(financeDetailForm.getLoanOrderId());
        if (loanOrderDO != null) {
            loanOrderDO.setDiscountAmount(financeDetailForm.getDiscountAmount());
            loanOrderDO.setLoanAmount(financeDetailForm.getLoanAmount());
            loanOrderDO.setFreightAmount(financeDetailForm.getFreightAmount());
            loanOrderDO.setOtherDiscount(financeDetailForm.getOtherDiscount());
            loanOrderDO.setInterestAmount(financeDetailForm.getInterestAmount());
            loanOrderDO.setId(financeDetailForm.getLoanOrderId());
            loanOrderManager.updateByPrimaryKeySelective(loanOrderDO);
        }
    }

    private void insertOrUpdateEditDO(List<OrderInfoDO> list, EditLoanOrderForm editLoanOrderForm, CarSnapDO carSnapDO) {

        try {
            // b2b_order表数据
            loanOrderAOFacade.setOrder(editLoanOrderForm);
            // b2b_loan_order表数据
            loanOrderAOFacade.setLoanOrder(editLoanOrderForm);
            //
            loanOrderAOFacade.setOrderInfo(editLoanOrderForm, list);
            // b2b_car_snap表数据
            loanOrderAOFacade.setCarSnap(editLoanOrderForm, carSnapDO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    LoanOrderDO assemblyLoanOrder(LoanOrderDO loanOrderDO, EditLoanOrderForm editLoanOrderForm) {
        loanOrderDO.setDespositAmount(PriceUtil.convertPriceYuanWithComma(editLoanOrderForm.getDespositAmount()));
        loanOrderDO.setTotalAmount(PriceUtil.convertPriceYuanWithComma(editLoanOrderForm.getTotalAmount()));

        return loanOrderDO;
    }

    CarSnapDO getCarSanpDOByLoanOrder(Long loanOrderId) {
        CarSnapQuery query = new CarSnapQuery();
        query.or().andLoanOrderIdEqualTo(loanOrderId);
        List<CarSnapDO> list = carSnapManager.selectByQuery(query);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }
    }

    /**
     * 查询订单宝信
     *
     * @param queryLoanOrderForm
     * @return
     */
    @Override
    public BizResult queryLoanOrders(QueryLoanOrderForm queryLoanOrderForm) {
        BizResult result = new BizResult();
        if (null == queryLoanOrderForm || queryLoanOrderForm.getPageNo() < 1) {
            result.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return result;
        }
        try {
            if (StringUtil.isNotEmpty(queryLoanOrderForm.getStartTimeMsg())
                    && StringUtil.isNotEmpty(queryLoanOrderForm.getEndTimeMsg())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                queryLoanOrderForm.setApplyStartTime(sdf.parse(queryLoanOrderForm.getStartTimeMsg() + " 00:00:00"));
                queryLoanOrderForm.setApplyEndTime(sdf.parse(queryLoanOrderForm.getEndTimeMsg() + " 23:59:59"));
            }
            if (StringUtil.isNotEmpty(queryLoanOrderForm.getStatuses())) {
                String[] statuses = queryLoanOrderForm.getStatuses().split(",");
                List<Integer> statusValues = new ArrayList<>();
                for (String status : statuses) {
                    if (StringUtil.isNotEmpty(status)) {
                        Integer value = Integer.valueOf(status);
                        statusValues.add(value);
                    }
                }
                if (null != statusValues && !statusValues.isEmpty()) {
                    queryLoanOrderForm.setStatusValues(statusValues);
                }
            }
            LoanOrderQuery loanOrderQuery = this.assemblyQuery(queryLoanOrderForm);
            if (null == loanOrderQuery) {
                result.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
                return result;
            }
            List<LoanOrderDO> loanOrderDOs = loanOrderManager.selectByQuery(loanOrderQuery);
            if (null == loanOrderDOs) {
                result.setResultCodeAndMsg(BaseConstants.ResultCode.QUERY_FAIL);
                return result;
            }
            List<LoanOrderDTO> loanOrderDTOs = new ArrayList<>();
            LoanOrderDTO loanOrderDTO;
            OrderDO orderDO;
            CarSnapDO carSnapDO;
            UserDO userDO;
            ShippingOrderDO shippingOrderDO;
            LogisticsCompanyDO logisticsCompanyDO = null;
            for (LoanOrderDO loanOrderDO : loanOrderDOs) {
                orderDO = orderManager.selectByPrimaryKey(loanOrderDO.getOutOrderId());
                carSnapDO = carSnapManager.selectByLoanOrderId(loanOrderDO.getId());
                userDO = userManager.selectByPrimaryKey(loanOrderDO.getBuyerId());
                shippingOrderDO = shippingOrderManager.selectByOutOrderId(loanOrderDO.getId());
                if (null != shippingOrderDO && null != shippingOrderDO.getLogisticsCompanyId() && shippingOrderDO.getLogisticsCompanyId() > 0) {
                    logisticsCompanyDO = logisticsCompanyManager.selectByPrimaryKey(shippingOrderDO.getLogisticsCompanyId());
                }
                loanOrderDTO = new LoanOrderDTO();
                loanOrderDTO.setLoanOrderDO(loanOrderDO);
                loanOrderDTO.setOrderDO(orderDO);
                loanOrderDTO.setCarSnapDO(carSnapDO);
                loanOrderDTO.setUserDO(userDO);
                loanOrderDTO.setShippingOrderDO(shippingOrderDO);
                loanOrderDTO.setLogisticsCompanyDO(logisticsCompanyDO);
                this.getLoanOrderFinances(loanOrderDTO);
                this.getLoanOrderInfos(loanOrderDTO);
                loanOrderDTOs.add(loanOrderDTO);
            }
            PageResult<LoanOrderDTO> pageResult = new PageResult<>();
            pageResult.setPageSize(queryLoanOrderForm.getPageSize());
            pageResult.setPageNo(queryLoanOrderForm.getPageNo());
            pageResult.setTotalCount(loanOrderManager.countByQuery(loanOrderQuery));
            pageResult.setResult(loanOrderDTOs);
            result.setResultDate(pageResult);
            result.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return result;
    }

    @Override
    public void exportLoanOrders(ExportLoanOrderForm exportLoanOrderForm) {
        try {
            BizResult bizResult = queryLoanOrders(exportLoanOrderForm.getQueryLoanOrderForm());
            if (null == bizResult || !bizResult.isSuccess()) {
                return;
            }
            List<LoanOrderDTO> loanOrderDTOs = ((PageResult<LoanOrderDTO>) bizResult.getResultData()).getResult();
            Workbook workbook = new XSSFWorkbook();
            setExcelStyle(workbook);
            String[] headers = {"订单宝号", "创建时间", "车型", "外观", "内饰", "申请公司", "申请人", "联系电话", "业务经理",
                    "供应商", "合同价", "定金", "保证金", "利息", "代付运费", "其他优惠", "优惠说明", "供应商打款时间", "发车时间", "接车时间", "提车时间", "物流公司"};
            setClues(workbook, headers, loanOrderDTOs);
            workbook.write(exportLoanOrderForm.getOutputStream());
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    // 标题字体
    private Font titleFont = null;
    // 标题样式
    private CellStyle titleStyle = null;
    // 行信息内容样式
    private CellStyle contentStyle = null;

    /**
     * 样式初始化
     */
    private void setExcelStyle(Workbook workBook) {
        // 设置列标题字体，样式
        titleFont = workBook.createFont();
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 标题列样式
        titleStyle = workBook.createCellStyle();
        titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); // 设置边框
        titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyle.setFont(titleFont);
        // 内容列样式
        contentStyle = workBook.createCellStyle();
        contentStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        contentStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        contentStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        contentStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
    }

    private void setClues(Workbook workbook, String[] headers, List<LoanOrderDTO> loanOrderDTOs) {
        Sheet sheet = workbook.createSheet("订单宝列表");// 创建新的sheet对象
        Row sheetRow = sheet.createRow((short) 0);
        Cell cell = null;
        for (int i = 0, len = headers.length; i < len; i++) {
            cell = sheetRow.createCell(i);
            cell.setCellStyle(titleStyle);//设置标题样式
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(headers[i]);
        }
        Row row;
        LoanOrderDTO loanOrderDTO;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String modelName, payTime, outerColorName, innerColorName, realName, loginName, postTime, recerveTime, shippingTime;
        for (int i = 1, len = loanOrderDTOs.size(); i <= len; i++) {
            loanOrderDTO = loanOrderDTOs.get(i - 1);
            row = sheet.createRow((short) i);
            row.setHeightInPoints(20);
            int colNum = 0;
            if (null == loanOrderDTO.getCarSnapDO()) {
                modelName = "";
                outerColorName = "";
                innerColorName = "";
            } else {
                modelName = loanOrderDTO.getCarSnapDO().getModelName();
                outerColorName = loanOrderDTO.getCarSnapDO().getOuterColorName();
                innerColorName = loanOrderDTO.getCarSnapDO().getInnerColorName();
            }
            if (null == loanOrderDTO.getUserDO()) {
                realName = "";
                loginName = "";
            } else {
                realName = loanOrderDTO.getUserDO().getRealName();
                loginName = loanOrderDTO.getUserDO().getLoginName();
            }
            if (null != loanOrderDTO.getPayDOs() && !loanOrderDTO.getPayDOs().isEmpty()) {
                if (loanOrderDTO.getPayDOs().get(0).getPayTime() != null) {
                    payTime = sdf.format(loanOrderDTO.getPayDOs().get(0).getPayTime());
                } else {
                    payTime = "";
                }
            } else {
                payTime = "";
            }
            if (null == loanOrderDTO.getShippingOrderDO()) {
                postTime = "";
                recerveTime = "";
                shippingTime = "";
            } else {
                if (null != loanOrderDTO.getShippingOrderDO().getActualPostTime()) {
                    postTime = sdf.format(loanOrderDTO.getShippingOrderDO().getActualPostTime());
                } else {
                    postTime = "";
                }
                if (null != loanOrderDTO.getShippingOrderDO().getActualRecerveTime()) {
                    recerveTime = sdf.format(loanOrderDTO.getShippingOrderDO().getActualRecerveTime());
                } else {
                    recerveTime = "";
                }
                if (null != loanOrderDTO.getShippingOrderDO().getShippingTime()) {
                    shippingTime = sdf.format(loanOrderDTO.getShippingOrderDO().getShippingTime());
                } else {
                    shippingTime = "";
                }
            }
            createCell(cell, row, colNum, loanOrderDTO.getLoanOrderDO().getOrderNo());
            createCell(cell, row, ++colNum, sdf.format(loanOrderDTO.getLoanOrderDO().getGmtCreate()));
            createCell(cell, row, ++colNum, modelName);
            createCell(cell, row, ++colNum, outerColorName);
            createCell(cell, row, ++colNum, innerColorName);
            createCell(cell, row, ++colNum, loanOrderDTO.getLoanOrderDO().getDealerName());
            createCell(cell, row, ++colNum, realName);
            createCell(cell, row, ++colNum, loginName);
            createCell(cell, row, ++colNum, loanOrderDTO.getLoanOrderDO().getManager());
            createCell(cell, row, ++colNum, loanOrderDTO.getLoanOrderDO().getProviderName());
            createCell(cell, row, ++colNum, PriceUtil.formatCNY(loanOrderDTO.getLoanOrderDO().getTotalAmount()));
            createCell(cell, row, ++colNum, PriceUtil.formatCNY(loanOrderDTO.getLoanOrderDO().getDespositAmount()));
            createCell(cell, row, ++colNum, PriceUtil.formatCNY(loanOrderDTO.getLoanOrderDO().getMarginAmount()));
            createCell(cell, row, ++colNum, PriceUtil.formatCNY(loanOrderDTO.getLoanOrderDO().getInterestAmount()));
            createCell(cell, row, ++colNum, PriceUtil.formatCNY(loanOrderDTO.getLoanOrderDO().getFreightAmount()));
            createCell(cell, row, ++colNum, loanOrderDTO.getLoanOrderDO().getOtherDiscount());
            createCell(cell, row, ++colNum, "");
            createCell(cell, row, ++colNum, payTime);
            createCell(cell, row, ++colNum, postTime);
            createCell(cell, row, ++colNum, recerveTime);
            createCell(cell, row, ++colNum, shippingTime);
            createCell(cell, row, ++colNum, loanOrderDTO.getLogisticsCompanyDO() == null ? "" : loanOrderDTO.getLogisticsCompanyDO().getCompanyName());
        }
    }

    private void createCell(Cell cell, Row row, int colNum, String value) {
        cell = row.createCell(colNum);
        cell.setCellStyle(titleStyle);
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(value == null ? "" : value);
    }

    public LoanOrderDO queryLoanOrderByOutOrderId(Long outOrderId) {
        LoanOrderQuery query = new LoanOrderQuery();
        query.createCriteria().andOutOrderIdEqualTo(outOrderId);
        List<LoanOrderDO> ls = loanOrderManager.selectByQuery(query);
        LoanOrderDO loanOrderDO = new LoanOrderDO();
        if (!CollectionUtils.isEmpty(ls)) {
            loanOrderDO = ls.get(0);
        }
        return loanOrderDO;
    }

    @Override
    public LoanOrderDO queryById(Long id) {
        return loanOrderManager.selectByPrimaryKey(id);
    }

    /**
     * 获取订单宝信息
     *
     * @param id
     * @return
     */
    @Override
    public BizResult queryLoanOrderById(Long id) {
        BizResult result = new BizResult();
        if (null == id || id < 1L) {
            result.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return result;
        }
        try {
            LoanOrderDTO loanOrderDTO = new LoanOrderDTO();
            LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(id);
            if (null == loanOrderDO) {
                result.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
                return result;
            }
            loanOrderDTO.setLoanOrderDO(loanOrderDO);
            OrderDO orderDO = orderManager.selectByPrimaryKey(loanOrderDO.getOutOrderId());
            loanOrderDTO.setOrderDO(orderDO);
            UserDO userDO = userManager.selectByPrimaryKey(loanOrderDO.getBuyerId());
            loanOrderDTO.setUserDO(userDO);
            CarSnapDO carSnapDO = carSnapManager.selectByLoanOrderId(loanOrderDO.getId());
            loanOrderDTO.setCarSnapDO(carSnapDO);
            //相关图片信息
            this.getLoanOrderInfos(loanOrderDTO);
            //相关财务信息
            this.getLoanOrderFinances(loanOrderDTO);
            //物流信息
            ShippingOrderDO shippingOrderDO = shippingOrderManager.selectByOutOrderId(loanOrderDO.getId());
            loanOrderDTO.setShippingOrderDO(shippingOrderDO);
            if (null != shippingOrderDO && null != shippingOrderDO.getLogisticsCompanyId() && shippingOrderDO.getLogisticsCompanyId() > 0) {
                LogisticsCompanyDO logisticsCompanyDO = logisticsCompanyManager.selectByPrimaryKey(shippingOrderDO.getLogisticsCompanyId());
                loanOrderDTO.setLogisticsCompanyDO(logisticsCompanyDO);
            }
            CarFormalitiesDO carFormalitiesDO = carFormalitiesManager.selectByOutOrderId(loanOrderDO.getId());
            loanOrderDTO.setCarFormalitiesDO(carFormalitiesDO);
            PartnerDO providerDO = partnerManager.selectByPrimaryKey(loanOrderDO.getProviderId());
            loanOrderDTO.setProviderDO(providerDO);
            result.setResultDate(loanOrderDTO);
            result.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return result;
    }

    private void getLoanOrderInfos(LoanOrderDTO loanOrderDTO) {
        OrderInfoQuery orderInfoQuery = new OrderInfoQuery();
        OrderInfoQuery.Criteria criteria = orderInfoQuery.createCriteria();
        criteria.andBizTypeEqualTo(InfoBizTypeEnum.LoanOrder.name());
        criteria.andBizIdEqualTo(loanOrderDTO.getLoanOrderDO().getId());
        orderInfoQuery.clearPage();
        List<OrderInfoDO> orderInfoDOs = orderInfoManager.selectByQuery(orderInfoQuery);
        if (null != orderInfoDOs && !orderInfoDOs.isEmpty()) {
            String infoType;
            for (OrderInfoDO orderInfoDO : orderInfoDOs) {
                if (null != orderInfoDO) {
                    infoType = orderInfoDO.getInfoType();
                    if (infoType.equals(InfoTypeEnum.DepositImgs.name())) {
                        loanOrderDTO.setDepositInfoDO(orderInfoDO);
                    } else if (infoType.equals(InfoTypeEnum.DaifuImgs.name())) {
                        loanOrderDTO.setDaifuInfoDO(orderInfoDO);
                    } else if (infoType.equals(InfoTypeEnum.DaigouImgs.name())) {
                        loanOrderDTO.setDaigouInfoDO(orderInfoDO);
                    } else if (infoType.equals(InfoTypeEnum.MarginImgs.name())) {
                        loanOrderDTO.setMarginInfoDO(orderInfoDO);
                    } else if (infoType.equals(InfoTypeEnum.ContractImgs.name())) {
                        loanOrderDTO.setContractInfoDO(orderInfoDO);
                    }
                }
            }
        }
    }

    private void getLoanOrderFinances(LoanOrderDTO loanOrderDTO) {
        //相关财务信息
        FinanceFlowQuery financeFlowQuery = new FinanceFlowQuery();
        FinanceFlowQuery.Criteria financeCriteria = financeFlowQuery.createCriteria();
        financeCriteria.andLoanOrderIdEqualTo(loanOrderDTO.getLoanOrderDO().getId());
        financeCriteria.andStatusNotEqualTo(-1);
        financeFlowQuery.clearPage();
        List<FinanceFlowDO> financeFlowDOs = financeFlowManager.selectByQuery(financeFlowQuery);
        if (null != financeFlowDOs && !financeFlowDOs.isEmpty()) {
            List<FinanceFlowDO> providerPayDOs = new ArrayList<>();
            List<FinanceFlowDO> marginDOs = new ArrayList<>();
            List<FinanceFlowDO> loanRepayDOs = new ArrayList<>();
            List<FinanceFlowDO> payDOs = new ArrayList<>();
            String bizType;
            for (FinanceFlowDO financeFlowDO : financeFlowDOs) {
                if (null != financeFlowDO) {
                    bizType = financeFlowDO.getBizType();
                    if (bizType.equals(FinanceBizTypeEnum.ProviderPay.name())) {
                        providerPayDOs.add(financeFlowDO);
                    } else if (bizType.equals(FinanceBizTypeEnum.Margin.name())) {
                        marginDOs.add(financeFlowDO);
                    } else if (bizType.equals(FinanceBizTypeEnum.LoanRepay.name())) {
                        loanRepayDOs.add(financeFlowDO);
                    } else if (bizType.equals(FinanceBizTypeEnum.Pay.name())) {
                        payDOs.add(financeFlowDO);
                    }
                }
            }
            loanOrderDTO.setProviderPayDOs(providerPayDOs);
            loanOrderDTO.setMarginDOs(marginDOs);
            loanOrderDTO.setLoanRepayDOs(loanRepayDOs);
            loanOrderDTO.setPayDOs(payDOs);
        }
    }

    /**
     * 订单宝详情信息(编辑页面)
     *
     * @param id
     * @return
     */
    @Override
    public BizResult queryEditLoanOrderById(Long id) {
        BizResult result = new BizResult();
        if (null == id || id < 1L) {
            result.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return result;
        }
        EditLoanOrderForm editLoanOrderForm = new EditLoanOrderForm();
        editLoanOrderForm.setId(id);
        // 获取订单宝信息
        LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(id);
        if (loanOrderDO == null) {
            logger.error(LoanOrderErrorEnum.NO_LOAN_ORDRE_ERR.getMsg() + ", 订单宝ID=" + id);
            result.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
            return result;
        }
        // 对垫资金额的梳理
        if (loanOrderDO.getLoanAmount() == null) {
            if (loanOrderDO.getTotalAmount() != null && loanOrderDO.getDespositAmount() != null) {
                loanOrderDO.setLoanAmount(loanOrderDO.getTotalAmount().longValue() - loanOrderDO.getDespositAmount().longValue());
            }
        }
        // 对日利率的输入
        BigDecimal interestRate = loanOrderDO.getInterestRate();
        if (interestRate != null) {
            editLoanOrderForm.setInterestRate(interestRate);
        }
        // 获取订单信息
        Long orderId = loanOrderDO.getOutOrderId();
        if (orderId == null) {
            logger.error(LoanOrderErrorEnum.NO_ORDER_ERR.getMsg() + ", 订单宝ID=" + id);
            result.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
            return result;
        }
        OrderDO orderDO = orderManager.selectByPrimaryKey(orderId);
        if (orderDO == null) {
            logger.error(BaseConstants.getMessage(BaseConstants.ResultCode.NO_DATA) + ", [order_id=" + id + "]");
            result.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
            return result;
        }
        OrderInfoQuery query = new OrderInfoQuery();
        query.createCriteria().andBizIdEqualTo(loanOrderDO.getId());
        List<OrderInfoDO> list = orderInfoManager.selectByQuery(query);
        OrderInfoDO orderInfoDO = new OrderInfoDO();
        if (list == null || list.size() == 0) {
            logger.info("查询b2b_order_info" + BaseConstants.getMessage(BaseConstants.ResultCode.NO_DATA) + ", [loan_order_id=" + id + "]");
        } else {
            for (OrderInfoDO item : list) {
                if (InfoTypeEnum.DaifuImgs.name().equals(item.getInfoType())) {
                    // 代付凭证
                    editLoanOrderForm.setDaifuImgs(ImgUrlUtil.parseList(item.getInfoValue()));
                }
                if (InfoTypeEnum.DepositImgs.name().equals(item.getInfoType())) {
                    // 定金凭证
                    editLoanOrderForm.setDespositImgs(ImgUrlUtil.parseList(item.getInfoValue()));
                }
            }
        }

        // 获取车辆信息
        Long carId = orderDO.getCarId();
        CarSnapDO carSnapDO = carSnapManager.selectByLoanOrderId(loanOrderDO.getId());
        if (carId == null) {
            logger.info(BaseConstants.getMessage(BaseConstants.ResultCode.PARAM_ERROR) + ", 该订单宝[" + id + "]无对应的订单号");
        }
        /**
         * 组装数据
         */
        UserDO userDO = new UserDO();
        try {
            userDO = userManager.selectByPrimaryKey(loanOrderDO.getBuyerId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        editLoanOrderForm.setUserDO(userDO);
        editLoanOrderForm.setLoanOrderDO(loanOrderDO);
        editLoanOrderForm.setOrderDO(orderDO);
        editLoanOrderForm.setCarSnapDO(carSnapDO);
        // 备注
        editLoanOrderForm.setMemo(orderInfoDO.getMemo());

        result.setResultDate(editLoanOrderForm);
        return result;
    }

    @Override
    public BizResult queryPartnerList(QueryPartnerForm queryPartnerForm) {
        BizResult result = new BizResult();
        if (null == queryPartnerForm) {
            result.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return result;
        }
        try {
            List<Integer> types = new ArrayList<>(2);
            types.add(PartnerTypeEnum.dealer.getCode());
            types.add(PartnerTypeEnum.dealerAndProvider.getCode());
            queryPartnerForm.setTypes(types);
            queryPartnerForm.setPageSize(5);
            PartnerQuery partnerQuery = this.assemblyQuery(queryPartnerForm);
            if (null == partnerQuery) {
                result.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
                return result;
            }
            PageResult<PartnerDO> pageResult = partnerManager.selectByQueryWithPage(partnerQuery);
            if (null == pageResult) {
                result.setResultCodeAndMsg(BaseConstants.ResultCode.QUERY_FAIL);
                return result;
            }
            result.setResultDate(pageResult);
            result.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return result;
    }

    @Override
    public BizResult editLoanOrderProviderView(Long id) {
        BizResult bizResult = new BizResult();
        if (null == id || id < 1L) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return bizResult;
        }
        try {
            LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(id);
            if (null == loanOrderDO) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
                return bizResult;
            }
            PartnerDO providerDO = partnerManager.selectByPrimaryKey(loanOrderDO.getProviderId());
            OrderDO orderDO = orderManager.selectByPrimaryKey(loanOrderDO.getOutOrderId());
            EditLoanOrderPartnerForm editLoanOrderPartnerForm = new EditLoanOrderPartnerForm();
            editLoanOrderPartnerForm.setId(loanOrderDO.getId());
            editLoanOrderPartnerForm.setInvoiceType(orderDO.getInvoiceType());
            if (null != orderDO.getGmtOfferTime()) {
                editLoanOrderPartnerForm.setOfferTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderDO.getGmtOfferTime()));
            }
            editLoanOrderPartnerForm.setProviderId(loanOrderDO.getProviderId());
            editLoanOrderPartnerForm.setProviderName(loanOrderDO.getProviderName());
            editLoanOrderPartnerForm.setProviderContractName(null == providerDO ? null : providerDO.getContactsName());
            editLoanOrderPartnerForm.setProviderContractPhone(null == providerDO ? null : providerDO.getContactsPhone());

            FinanceFlowQuery query = new FinanceFlowQuery();
            FinanceFlowQuery.Criteria criteria = query.createCriteria();
            query.clearPage();
            criteria.andBizTypeEqualTo(FinanceBizTypeEnum.ProviderPay.name());
            criteria.andLoanOrderIdEqualTo(loanOrderDO.getId());
            List<FinanceFlowDO> financeFlowDOs = financeFlowManager.selectByQuery(query);
            OrderInfoQuery orderInfoQuery = new OrderInfoQuery();
            OrderInfoQuery.Criteria orderInfoCriteria = orderInfoQuery.createCriteria();
            orderInfoCriteria.andBizTypeEqualTo(InfoBizTypeEnum.LoanOrder.name());
            orderInfoCriteria.andBizIdEqualTo(loanOrderDO.getId());
            orderInfoQuery.clearPage();
            List<OrderInfoDO> orderInfoDOs = orderInfoManager.selectByQuery(orderInfoQuery);
            if (null != orderInfoDOs && !orderInfoDOs.isEmpty()) {
                for (OrderInfoDO orderInfoDO : orderInfoDOs) {
                    if (orderInfoDO.getInfoType().equals(InfoTypeEnum.DaigouImgs.name())) {
                        editLoanOrderPartnerForm.setDaigouImgs(ImgUrlUtil.parseList(orderInfoDO.getInfoValue()));
                    } else if (orderInfoDO.getInfoType().equals(InfoTypeEnum.ContractImgs.name())) {
                        editLoanOrderPartnerForm.setContractImgs(ImgUrlUtil.parseList(orderInfoDO.getInfoValue()));
                    }
                }
            }
            bizResult.setKeyData("financeFlowDOs", financeFlowDOs);
            bizResult.setResultDate(editLoanOrderPartnerForm);
            bizResult.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return bizResult;
    }

    @Override
    public BizResult editLoanOrderProvider(final EditLoanOrderPartnerForm editLoanOrderPartnerForm) {
        BizResult bizResult = new BizResult();
        if (null == editLoanOrderPartnerForm || null == editLoanOrderPartnerForm.getId() || editLoanOrderPartnerForm.getId() < 1L
                || null == editLoanOrderPartnerForm.getProviderId() || editLoanOrderPartnerForm.getProviderId() < 1L
                || StringUtil.isEmpty(editLoanOrderPartnerForm.getProviderName())
                || StringUtil.isEmpty(editLoanOrderPartnerForm.getInvoiceType())
                || StringUtil.isEmpty(editLoanOrderPartnerForm.getOfferTime())) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return bizResult;
        }
        try {
            LoanOrderDO currentLoanOrderDO = loanOrderManager.selectByPrimaryKey(editLoanOrderPartnerForm.getId());
            if (null == currentLoanOrderDO) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
                return bizResult;
            }
            editLoanOrderPartnerForm.setOutOrderId(currentLoanOrderDO.getOutOrderId());
            LoanOrderDO loanOrderDO = this.assemblyLoanOrderDO(editLoanOrderPartnerForm);
            if (null == loanOrderDO) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
                return bizResult;
            }
            OrderDO orderDO = this.assemblyOrderDO(editLoanOrderPartnerForm);
            if (null == orderDO) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
                return bizResult;
            }
            if (loanOrderManager.updateByPrimaryKeySelective(loanOrderDO) != 1) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.UPDATE_FAIL);
                return bizResult;
            }
            if (orderManager.updateByPrimaryKeySelective(orderDO) != 1) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.UPDATE_FAIL);
                return bizResult;
            }
            this.updateProviderImgs(editLoanOrderPartnerForm.getDaigouImgs(), editLoanOrderPartnerForm.getId(), InfoTypeEnum.DaigouImgs);
            this.updateProviderImgs(editLoanOrderPartnerForm.getContractImgs(), editLoanOrderPartnerForm.getId(), InfoTypeEnum.ContractImgs);
            List<FinanceFlowDO> addFinances = this.assemblyFinanceFlowDOs(editLoanOrderPartnerForm, 1);
            List<FinanceFlowDO> updateFinances = this.assemblyFinanceFlowDOs(editLoanOrderPartnerForm, 2);
            if (null != addFinances && !addFinances.isEmpty()) {
                for (FinanceFlowDO financeFlowDO : addFinances) {
                    financeFlowManager.insertSelective(financeFlowDO);
                }
            }
            if (null != updateFinances && !updateFinances.isEmpty()) {
                for (FinanceFlowDO financeFlowDO : updateFinances) {
                    financeFlowManager.updateByPrimaryKeySelective(financeFlowDO);
                }
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    actLogAO.addLog(ActLogBizTypeEnum.LoanOrder, editLoanOrderPartnerForm.getId(), "编辑供应商信息", ActLogActorNameEnum.updateProviderInfo);
                }
            }).start();
            bizResult.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return bizResult;
    }

    private void updateProviderImgs(List<String> imgs, Long loanOrderId, InfoTypeEnum infoTypeEnum) {
        if (null == loanOrderId || loanOrderId < 1L || null == infoTypeEnum) {
            return;
        }
        OrderInfoDO orderInfoDO;
        if (null != imgs && !imgs.isEmpty()) {
            OrderInfoQuery orderInfoQuery = new OrderInfoQuery();
            OrderInfoQuery.Criteria orderInfoCriteria = orderInfoQuery.createCriteria();
            orderInfoCriteria.andBizTypeEqualTo(InfoBizTypeEnum.LoanOrder.name());
            orderInfoCriteria.andBizIdEqualTo(loanOrderId);
            orderInfoCriteria.andInfoTypeEqualTo(infoTypeEnum.name());
            List<OrderInfoDO> infoDOs = orderInfoManager.selectByQuery(orderInfoQuery);
            if (null != infoDOs && !infoDOs.isEmpty()) {
                orderInfoDO = infoDOs.get(0);
                if (orderInfoDO.getInfoStatus().intValue() != InfoStatusEnum.pass.getStatus()) {
                    orderInfoDO = new OrderInfoDO();
                    orderInfoDO.setInfoValue(ImgUrlUtil.mergeList(imgs));
                    orderInfoManager.updateByQuerySelective(orderInfoDO, orderInfoQuery);
                }
            } else {
                orderInfoDO = new OrderInfoDO();
                orderInfoDO.setBizType(InfoBizTypeEnum.LoanOrder.name());
                orderInfoDO.setBizId(loanOrderId);
                orderInfoDO.setInfoType(infoTypeEnum.name());
                orderInfoDO.setInfoValue(ImgUrlUtil.mergeList(imgs));
                orderInfoDO.setInfoStatus(InfoStatusEnum.init.getStatus());
                orderInfoManager.insertSelective(orderInfoDO);
            }
        }
    }

    @Override
    public BizResult approveImgsView(ApproveLoanOrderForm approveLoanOrderForm) {
        BizResult bizResult = new BizResult();
        if (null == approveLoanOrderForm || null == approveLoanOrderForm.getOrderId()
                || approveLoanOrderForm.getOrderId() < 1L || StringUtil.isEmpty(approveLoanOrderForm.getTypeName())) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return bizResult;
        }
        try {
            LoanOrderQuery loanOrderQuery = new LoanOrderQuery();
            LoanOrderQuery.Criteria loanOrderCriteria = loanOrderQuery.createCriteria();
            loanOrderCriteria.andIdEqualTo(approveLoanOrderForm.getOrderId());
            if (loanOrderManager.countByQuery(loanOrderQuery) != 1) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
                return bizResult;
            }
            OrderInfoQuery orderInfoQuery = new OrderInfoQuery();
            OrderInfoQuery.Criteria orderInfoCriteria = orderInfoQuery.createCriteria();
            orderInfoCriteria.andBizTypeEqualTo(InfoBizTypeEnum.LoanOrder.name());
            orderInfoCriteria.andBizIdEqualTo(approveLoanOrderForm.getOrderId());
            orderInfoCriteria.andInfoTypeEqualTo(InfoTypeEnum.getNameByType(approveLoanOrderForm.getTypeName()));
            orderInfoQuery.clearPage();
            List<OrderInfoDO> orderInfoDOs = orderInfoManager.selectByQuery(orderInfoQuery);
            if (null != orderInfoDOs && !orderInfoDOs.isEmpty()) {
                OrderInfoDO orderInfoDO = orderInfoDOs.get(0);
                approveLoanOrderForm.setImgs(ImgUrlUtil.parseList(orderInfoDO.getInfoValue()));
                approveLoanOrderForm.setStatus(orderInfoDO.getInfoStatus());
                approveLoanOrderForm.setMemo(orderInfoDO.getMemo());
            }
            approveLoanOrderForm.setTypeDesc(InfoTypeEnum.getDescByType(approveLoanOrderForm.getTypeName()));
            approveLoanOrderForm.setType(InfoTypeEnum.getNameByType(approveLoanOrderForm.getTypeName()));
            bizResult.setResultDate(approveLoanOrderForm);
            bizResult.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return bizResult;
    }

    @Override
    public BizResult approveLoanOrderImgs(final ApproveLoanOrderForm approveLoanOrderForm) {
        BizResult bizResult = new BizResult();
        if (null == approveLoanOrderForm || StringUtil.isEmpty(approveLoanOrderForm.getType())
                || null == approveLoanOrderForm.getOrderId() || approveLoanOrderForm.getOrderId() < 1L) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return bizResult;
        }
        try {
            final LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(approveLoanOrderForm.getOrderId());
            if (null == loanOrderDO) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
                return bizResult;
            }
            OrderInfoQuery orderInfoQuery = new OrderInfoQuery();
            OrderInfoQuery.Criteria criteria = orderInfoQuery.createCriteria();
            criteria.andBizTypeEqualTo(InfoBizTypeEnum.LoanOrder.name());
            criteria.andBizIdEqualTo(approveLoanOrderForm.getOrderId());
            criteria.andInfoTypeEqualTo(approveLoanOrderForm.getType());
            int count = orderInfoManager.countByQuery(orderInfoQuery);
            OrderInfoDO orderInfoDO = new OrderInfoDO();
            orderInfoDO.setBizType(InfoBizTypeEnum.LoanOrder.name());
            orderInfoDO.setBizId(approveLoanOrderForm.getOrderId());
            orderInfoDO.setInfoStatus(approveLoanOrderForm.getStatus());
            orderInfoDO.setMemo(approveLoanOrderForm.getMemo());
            orderInfoDO.setInfoType(approveLoanOrderForm.getType());
            orderInfoDO.setInfoValue(ImgUrlUtil.mergeList(approveLoanOrderForm.getImgs()));
            if (count == 0) {
                orderInfoManager.insertSelective(orderInfoDO);
            } else {
                orderInfoManager.updateByQuerySelective(orderInfoDO, orderInfoQuery);
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (approveLoanOrderForm.getStatus().intValue() == InfoStatusEnum.pass.getStatus()) {
                        userMsgAO.passInfo(loanOrderDO, InfoTypeEnum.getEnumByName(approveLoanOrderForm.getType()));
                    } else if (approveLoanOrderForm.getStatus().intValue() == InfoStatusEnum.reject.getStatus()) {
                        userMsgAO.rejectInfo(loanOrderDO, InfoTypeEnum.getEnumByName(approveLoanOrderForm.getType()), approveLoanOrderForm.getMemo());
                    }
                }
            }).start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String detail = InfoTypeEnum.getDescByName(approveLoanOrderForm.getType())
                            .concat(InfoStatusEnum.getDescByStatus(approveLoanOrderForm.getStatus()));
                    actLogAO.addLog(ActLogBizTypeEnum.LoanOrder, loanOrderDO.getId(), detail, ActLogActorNameEnum.auditLoanOrderPic);
                }
            }).start();
            bizResult.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return bizResult;
    }

    private LoanOrderQuery assemblyQuery(QueryLoanOrderForm queryLoanOrderForm) {
        if (null == queryLoanOrderForm) {
            return null;
        }
        LoanOrderQuery loanOrderQuery = new LoanOrderQuery();
        LoanOrderQuery.Criteria criteria = loanOrderQuery.createCriteria();
        loanOrderQuery.setPageNo(queryLoanOrderForm.getPageNo());
        loanOrderQuery.setPageSize(queryLoanOrderForm.getPageSize());
        if (queryLoanOrderForm.isQueryAll()) {
            loanOrderQuery.clearPage();
        }
        criteria.andIsDeletedNotEqualTo(true);
        if (StringUtil.isNotEmpty(queryLoanOrderForm.getOrderNo())) {
            criteria.andOrderNoLike("%" + queryLoanOrderForm.getOrderNo() + "%");
        }
        if (null != queryLoanOrderForm.getApplyStartTime() && null != queryLoanOrderForm.getApplyEndTime()
                && queryLoanOrderForm.getApplyStartTime().before(queryLoanOrderForm.getApplyEndTime())) {
            criteria.andGmtCreateBetween(queryLoanOrderForm.getApplyStartTime(), queryLoanOrderForm.getApplyEndTime());
        }
        if (StringUtil.isNotEmpty(queryLoanOrderForm.getDealerName())) {
            criteria.andDealerNameLike("%" + queryLoanOrderForm.getDealerName() + "%");
        }
        if (StringUtil.isNotEmpty(queryLoanOrderForm.getManager())) {
            criteria.andManagerLike(queryLoanOrderForm.getManager());
        }
        if (null != queryLoanOrderForm.getStatusValues() && !queryLoanOrderForm.getStatusValues().isEmpty()) {
            criteria.andStatusIn(queryLoanOrderForm.getStatusValues());
        }
        loanOrderQuery.setOrderByClause("id desc");
        return loanOrderQuery;
    }

    private PartnerQuery assemblyQuery(QueryPartnerForm queryPartnerForm) {
        if (null == queryPartnerForm) {
            return null;
        }
        PartnerQuery partnerQuery = new PartnerQuery();
        PartnerQuery.Criteria criteria = partnerQuery.createCriteria();
        partnerQuery.setPageNo(queryPartnerForm.getPageNo());
        partnerQuery.setPageSize(queryPartnerForm.getPageSize());
        criteria.andStatusEqualTo(PartnerStatusEnum.normal.getCode());
        if (StringUtil.isNotEmpty(queryPartnerForm.getCorpName())) {
            criteria.andCorpNameLike("%" + queryPartnerForm.getCorpName() + "%");
        }
        if (StringUtil.isNotEmpty(queryPartnerForm.getContactsName())) {
            criteria.andContactsNameLike("%" + queryPartnerForm.getContactsName() + "%");
        }
        if (StringUtil.isNotEmpty(queryPartnerForm.getContactsPhone())) {
            criteria.andContactsPhoneLike("%" + queryPartnerForm.getContactsPhone() + "%");
        }
        if (null != queryPartnerForm.getTypes() && !queryPartnerForm.getTypes().isEmpty()) {
            criteria.andTypeIn(queryPartnerForm.getTypes());
        }
        partnerQuery.setOrderByClause("id");
        return partnerQuery;
    }

    private LoanOrderDO assemblyLoanOrderDO(EditLoanOrderPartnerForm editLoanOrderPartnerForm) {
        if (null == editLoanOrderPartnerForm) {
            return null;
        }
        LoanOrderDO loanOrderDO = new LoanOrderDO();
        loanOrderDO.setId(editLoanOrderPartnerForm.getId());
        loanOrderDO.setProviderId(editLoanOrderPartnerForm.getProviderId());
        loanOrderDO.setProviderName(editLoanOrderPartnerForm.getProviderName());
        return loanOrderDO;
    }

    private OrderDO assemblyOrderDO(EditLoanOrderPartnerForm editLoanOrderPartnerForm) throws ParseException {
        if (null == editLoanOrderPartnerForm) {
            return null;
        }
        OrderDO orderDO = new OrderDO();
        orderDO.setId(editLoanOrderPartnerForm.getOutOrderId());
        orderDO.setProviderId(editLoanOrderPartnerForm.getProviderId());
        orderDO.setProviderName(editLoanOrderPartnerForm.getProviderName());
        if (StringUtil.isNotEmpty(editLoanOrderPartnerForm.getInvoiceType())) {
            orderDO.setInvoiceType(editLoanOrderPartnerForm.getInvoiceType());
        }
        if (StringUtil.isNotEmpty(editLoanOrderPartnerForm.getOfferTime())) {
            orderDO.setGmtOfferTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(editLoanOrderPartnerForm.getOfferTime()));
        }
        return orderDO;
    }

    private List<FinanceFlowDO> assemblyFinanceFlowDOs(EditLoanOrderPartnerForm editLoanOrderPartnerForm, int type) {
        if (null == editLoanOrderPartnerForm || null == editLoanOrderPartnerForm.getAccountNames()
                || null == editLoanOrderPartnerForm.getAccountNos() || null == editLoanOrderPartnerForm.getOpeningBanks()
                || null == editLoanOrderPartnerForm.getAmounts() || null == editLoanOrderPartnerForm.getFinanceTypes()) {
            return null;
        }
        List<FinanceFlowDO> financeFlowDOs = new ArrayList<>();
        FinanceFlowDO financeFlowDO = null;
        //AddLoanOrderFinanceForm addForm = null;
        for (int i = 0, len = editLoanOrderPartnerForm.getAccountNames().size(); i < len; i++) {
            //addForm = editLoanOrderPartnerForm.getAccountNames().get(i);
            Long id = editLoanOrderPartnerForm.getFinanceIds().get(i);
            financeFlowDO = new FinanceFlowDO();
            switch (type) {
                case 1://新增
                    if (null != id && id > 0L) {
                        continue;
                    }
                    break;
                case 2://修改
                    if (null == id || id < 1L) {
                        continue;
                    }
                    financeFlowDO.setId(id);
                    break;
            }
            financeFlowDO.setFinanceType(editLoanOrderPartnerForm.getFinanceTypes().get(i));
            financeFlowDO.setBizType(FinanceBizTypeEnum.ProviderPay.name());
            financeFlowDO.setLoanOrderId(editLoanOrderPartnerForm.getId());
            financeFlowDO.setAccountName(editLoanOrderPartnerForm.getAccountNames().get(i));
            financeFlowDO.setAccountNo(editLoanOrderPartnerForm.getAccountNos().get(i));
            financeFlowDO.setOpeningBank(editLoanOrderPartnerForm.getOpeningBanks().get(i));
            financeFlowDO.setAmount(editLoanOrderPartnerForm.getAmounts().get(i) * 100);
            financeFlowDO.setStatus(1);
            financeFlowDOs.add(financeFlowDO);
        }
        return financeFlowDOs;
    }

    @Override
    public com.maybach.dubbo.api.BizResult<Void> closeLoanOrder(Long orderId) {

        com.maybach.dubbo.api.BizResult<Void> result = new com.maybach.dubbo.api.BizResult<Void>();
        LoanOrderDO oldLoanOrder = loanOrderManager.selectByPrimaryKey(orderId);
        if (null == oldLoanOrder || oldLoanOrder.getIsDeleted() == true) {
            result.setMsg("订单宝不存在");
            logger.error("订单宝不存在[orderId={}]", orderId);
            return result;
        }

        if (oldLoanOrder.getStatus() == LoanOrderStatusEnum.init.getCode()) {
            LoanOrderDO loanOrderDO = new LoanOrderDO();
            loanOrderDO.setStatus(LoanOrderStatusEnum.closed.getCode());
            loanOrderDO.setId(orderId);
            loanOrderManager.updateByPrimaryKeySelective(loanOrderDO);
        }

        OrderDO oldOrder = orderManager.selectByPrimaryKey(oldLoanOrder.getOutOrderId());
        if (null == oldOrder) {
            result.setMsg("订单不存在");
            logger.error("订单不存在[orderId={}]", orderId);
            return result;
        }

        if (oldOrder.getStatus() != OrderStatusEnum.closed.getCode()) {
            OrderDO orderDO = new OrderDO();
            orderDO.setStatus(OrderStatusEnum.closed.getCode());
            orderDO.setId(orderId);
            orderManager.updateByPrimaryKeySelective(orderDO);
        }

        return result;
    }

    @Override
    public com.maybach.dubbo.api.BizResult<LoanOrderDetailModel> queryOrderDetail(Long loanOrderId) {
        com.maybach.dubbo.api.BizResult<LoanOrderDetailModel> result = new com.maybach.dubbo.api.BizResult<LoanOrderDetailModel>();
        // 基本信息
        LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(loanOrderId);
        OrderDO orderDO = orderManager.selectByPrimaryKey(loanOrderDO.getOutOrderId());

        CarSnapDO carSnapDO = getCarSanpDOByLoanOrder(loanOrderDO.getId());

        LoanOrderDetailModel detailModel = new LoanOrderDetailModel();
        detailModel.setCarOrderId(orderDO.getId());
        detailModel.setOrderId(loanOrderId);
        detailModel.setOrderNo(loanOrderDO.getOrderNo());
        detailModel.setOrderName(loanOrderDO.getOrderName());
        detailModel.setEmailAddress(loanOrderDO.getEmail());
        detailModel.setSupplier(loanOrderDO.getProviderName());
        detailModel.setCarNum(orderDO.getCarNum());
        detailModel.setStatus(loanOrderDO.getStatus());
        detailModel.setTatalAmount(loanOrderDO.getTotalAmount());
        detailModel.setGmtCreate(loanOrderDO.getGmtCreate());
        if (null != carSnapDO) {
            detailModel.setOuterColorName(carSnapDO.getOuterColorName());
            detailModel.setInnerColorName(carSnapDO.getInnerColorName());
            detailModel.setModel(carSnapDO.getModelName());
        }
        // 资料信息
        OrderInfoQuery query = new OrderInfoQuery();
        query.or().andBizTypeEqualTo(InfoBizTypeEnum.LoanOrder.name()).andBizIdEqualTo(loanOrderDO.getId());
        List<OrderInfoDO> list = orderInfoManager.selectByQuery(query);
        for (OrderInfoDO orderInfoDO : list) {
            InfoTypeEnum infoType = InfoTypeEnum.valueOf(orderInfoDO.getInfoType());
            switch (infoType) {
                case MarginImgs://保证金凭证照片
                    detailModel.setMarginInfo(assemblyOrderInfo(orderInfoDO));
                    break;
                case DepositImgs://定金凭证照片
                    detailModel.setDepositInfo(assemblyOrderInfo(orderInfoDO));
                    break;
                case ContractImgs://购车合同照片
                    detailModel.setContractInfo(assemblyOrderInfo(orderInfoDO));
                    break;
                case DaifuImgs://代付凭证图片
                    detailModel.setDaifuInfo(assemblyOrderInfo(orderInfoDO));
                    break;
                case DaigouImgs://代购协议图片
                    detailModel.setDaigouInfo(assemblyOrderInfo(orderInfoDO));
                    break;
            }
        }
        // 运输信息
        ShippingOrderDO shippingOrderDO = shippingOrderManager.selectByOutOrderId(loanOrderDO.getId());
        if (null != shippingOrderDO) {
            LogisticsModel model = this.assemblyModel(shippingOrderDO);
            detailModel.setLogisticsModel(model);
        }


        // 财物信息
        detailModel.setRepayInfos(this.assemblyFinanceModel(this.queryFinanceFlow(loanOrderId, Arrays.asList(FinanceBizTypeEnum.LoanRepay.name()))));

        detailModel.setPayInfos(this.assemblyFinanceModel(this.queryFinanceFlow(loanOrderId, Arrays.asList(FinanceBizTypeEnum.Pay.name()))));

        //detailModel.setEmailAddress();
        result.setResult(detailModel);

        return result;
    }

    List<FinanceFlowDO> queryFinanceFlow(Long orderId, List<String> bizType) {
        FinanceFlowQuery query = new FinanceFlowQuery();
        FinanceFlowQuery.Criteria criteria = query.or();
        criteria.andLoanOrderIdEqualTo(orderId);
        if (null != bizType && bizType.size() > 0) {
            criteria.andBizTypeIn(bizType);
        }
        criteria.andStatusNotEqualTo(-1);
        return financeFlowManager.selectByQuery(query);
    }


    FinanceFlowModel assemblyFinanceModel(FinanceFlowDO financeFlowDO) {
        FinanceFlowModel model = new FinanceFlowModel();
        model.setBizType(financeFlowDO.getBizType());
        model.setAccountName(financeFlowDO.getAccountName());
        model.setAccountNo(financeFlowDO.getAccountNo());
        model.setAmount(financeFlowDO.getAmount());
        model.setChargeNo(financeFlowDO.getChargeNo());
        model.setStatus(financeFlowDO.getStatus());
        model.setFinanceType(financeFlowDO.getFinanceType());
        model.setOpeningBank(financeFlowDO.getOpeningBank());
        model.setPayTime(financeFlowDO.getPayTime());
        model.setPayWay(financeFlowDO.getPayWay());
        model.setProfImgs(ImgUrlUtil.parseList(financeFlowDO.getProfImgs()));
        return model;
    }


    List<FinanceFlowModel> assemblyFinanceModel(List<FinanceFlowDO> list) {
        if (null == list) {
            return null;
        }
        List<FinanceFlowModel> result = new ArrayList<FinanceFlowModel>();

        for (FinanceFlowDO financeFlowDO : list) {
            result.add(this.assemblyFinanceModel(financeFlowDO));
        }
        return result;
    }


    private LogisticsModel assemblyModel(ShippingOrderDO shippingOrderDO) {

        LogisticsModel model = new LogisticsModel();
        model.setCompany(shippingOrderDO.getLogisticsCompany());
        model.setFee(shippingOrderDO.getAmount());
        model.setCheckCarImgs(ImgUrlUtil.parseList(shippingOrderDO.getCheckCarImgs()));
        model.setRecerveTime(shippingOrderDO.getActualRecerveTime());
        model.setSendTime(shippingOrderDO.getActualPostTime());
        model.setLogisticsNo(shippingOrderDO.getLogisticsNo());
        return model;
    }

    OrderInfoModel assemblyOrderInfo(OrderInfoDO orderInfoDO) {
        OrderInfoModel model = new OrderInfoModel();
        model.setId(orderInfoDO.getId());
        model.setOrderId(orderInfoDO.getBizId());
        model.setInfoType(orderInfoDO.getInfoType());
        model.setProfImgs(ImgUrlUtil.parseList(orderInfoDO.getInfoValue()));
        model.setInfoStatus(orderInfoDO.getInfoStatus());
        model.setMemo(orderInfoDO.getMemo());
        model.setGmtModified(orderInfoDO.getGmtModified());
        return model;
    }

    @Override
    public PageResult<LoanOrderModel> queryLoanOrder(LoanOrderQueryModel queryModel) {
        PageResult<LoanOrderModel> result = new PageResult<LoanOrderModel>();
        LoanOrderQuery query = new LoanOrderQuery();
        LoanOrderQuery.Criteria criteria = query.or();
        criteria.andIsDeletedEqualTo(false);
        if (null != queryModel.getBuyerId()) {
            criteria.andBuyerIdEqualTo(queryModel.getBuyerId());
        }
        if (!CollectionUtils.isEmpty(queryModel.getStatus())) {
            criteria.andStatusIn(queryModel.getStatus());
        }
        query.setOrderByClause(" id desc");
        //query.setPageNo(queryModel.getPageNo());
        query.setPageSize(queryModel.getPageSize());
        query.setPageOffset(queryModel.getStart());

        PageResult<LoanOrderDO> doResult = loanOrderManager.selectByQueryWithPage(query);
        result.setPageSize(doResult.getPageSize());
        result.setPageNo(doResult.getPageNo());
        result.setTotalCount(doResult.getTotalCount());

        List<LoanOrderModel> list = new ArrayList<LoanOrderModel>();

        for (LoanOrderDO loanOrderDO : doResult.getResult()) {
            OrderDO orderDO = orderManager.selectByPrimaryKey(loanOrderDO.getOutOrderId());
            CarSnapDO carSnapDO = carSnapManager.selectByLoanOrderId(loanOrderDO.getId());
            LoanOrderModel model = this.assemblyModel(loanOrderDO, orderDO, carSnapDO);
            list.add(model);
        }
        result.setResult(list);
        return result;
    }

    List<OrderInfoDO> getOrderInfo(Long orderId) {
        OrderInfoQuery query = new OrderInfoQuery();
        OrderInfoQuery.Criteria criteria = query.or();
        criteria.andBizIdEqualTo(orderId);
        criteria.andBizTypeEqualTo(InfoBizTypeEnum.LoanOrder.name());
        List<OrderInfoDO> list = orderInfoManager.selectByQuery(query);
        return list;
    }


    Integer getInfoStatus(List<OrderInfoDO> orderInfoDOs) {
        if (CollectionUtils.isEmpty(orderInfoDOs)) {
            return InfoStatusEnum.never.getStatus();
        }
        boolean hasInit = false;
        boolean hasReject = false;
        for (OrderInfoDO infoDO : orderInfoDOs) {
            if (infoDO.getInfoStatus() == InfoStatusEnum.init.getStatus()) {
                hasInit = true;
            } else if (infoDO.getInfoStatus() == InfoStatusEnum.reject.getStatus()) {
                hasReject = true;
            }
        }
        if (hasReject) {
            return InfoStatusEnum.reject.getStatus();
        } else if (orderInfoDOs.size() < 5) {
            return InfoStatusEnum.never.getStatus();
        } else if (hasInit) {
            return InfoStatusEnum.init.getStatus();
        }
        return InfoStatusEnum.pass.getStatus();
    }


    LoanOrderModel assemblyModel(LoanOrderDO loanOrderDO, OrderDO orderDO, CarSnapDO carSnapDO) {
        LoanOrderModel model = new LoanOrderModel();
        model.setOrderId(loanOrderDO.getId());
        model.setOrderName(loanOrderDO.getOrderName());
        model.setEmailAddress(loanOrderDO.getEmail());
        // TODO 合同金额 到底是是什么金额
        model.setContractAmount(loanOrderDO.getTotalAmount());
        model.setCarNum(orderDO.getCarNum());
        model.setGmtCreateTime(loanOrderDO.getGmtCreate());
        List<OrderInfoDO> orderInfoDOs = this.getOrderInfo(loanOrderDO.getId());
        model.setLatestStatus(this.getInfoStatus(orderInfoDOs));
        model.setStatus(loanOrderDO.getStatus());
        model.setSupplier(loanOrderDO.getProviderName());
        if (null != carSnapDO)
            model.setModel(carSnapDO.getModelName());
        // TODO 怎么查询
        return model;
    }

    @Override
    public com.maybach.dubbo.api.BizResult<Void> submitOrderInfo(OrderInfoModel model) {
        com.maybach.dubbo.api.BizResult<Void> result = new com.maybach.dubbo.api.BizResult<Void>();
        LoanOrderDO loanOrderDO = loanOrderManager.selectByPrimaryKey(model.getOrderId());
        if (null == loanOrderDO) {
            result.setMsg("订单宝不存在");
            logger.error("订单宝不存在[orderId={}]", model.getOrderId());
            return result;
        }


        OrderInfoQuery query = new OrderInfoQuery();
        OrderInfoQuery.Criteria criteria = query.or();
        criteria.andInfoTypeEqualTo(model.getInfoType());
        criteria.andBizIdEqualTo(loanOrderDO.getId());
        criteria.andBizTypeEqualTo(InfoBizTypeEnum.LoanOrder.name());
        List<OrderInfoDO> list = orderInfoManager.selectByQuery(query);
        if (CollectionUtils.isEmpty(list)) {
            OrderInfoDO infoDO = this.assemblyOrderInfo(model, loanOrderDO);
            infoDO.setInfoStatus(InfoStatusEnum.init.getStatus());
            orderInfoManager.insertSelective(infoDO);
        } else {
            //AssertUtil.isTrue(list.size() == 1, "list.size()== 1");
            OrderInfoDO oldInfo = list.get(0);

            if (oldInfo.getInfoStatus() == InfoStatusEnum.reject.getStatus()) {
                OrderInfoDO infoDO = this.assemblyOrderInfo(model, loanOrderDO);
                infoDO.setId(oldInfo.getId());
                infoDO.setInfoStatus(InfoStatusEnum.init.getStatus());
                orderInfoManager.updateByPrimaryKeySelective(infoDO);
            } else {
                if (model.getId() == null) {
                    result.setMsg("信息一存在重复提交");
                    logger.error("信息一存在重复提交[model={}]", model);
                } else {
                    result.setMsg("当前状态下不允许更新");
                    logger.error("当前状态下不允许更新[model={}]", model);
                }

                return result;
            }
        }

        return result;
    }

    OrderInfoDO assemblyOrderInfo(OrderInfoModel model, LoanOrderDO loanOrderDO) {
        OrderInfoDO infoDO = new OrderInfoDO();

        infoDO.setBizType(InfoBizTypeEnum.LoanOrder.name());
        infoDO.setBizId(loanOrderDO.getId());
        infoDO.setInfoType(model.getInfoType());
        infoDO.setMemo(model.getMemo());

        infoDO.setInfoValue(ImgUrlUtil.mergeList(model.getProfImgs()));

        return infoDO;
    }

    @Override
    public com.maybach.dubbo.api.BizResult<Integer> countOrder(Long buyerId, Integer status) {
        com.maybach.dubbo.api.BizResult<Integer> result = new com.maybach.dubbo.api.BizResult<Integer>();
        LoanOrderQuery query = new LoanOrderQuery();
        LoanOrderQuery.Criteria criteria = query.or();
        criteria.andIsDeletedEqualTo(false);
        criteria.andBuyerIdEqualTo(buyerId);
        if (null != status) {
            criteria.andStatusEqualTo(status);
        }
        Integer count = loanOrderManager.countByQuery(query);
        result.setResult(count);
        return result;
    }

    @Override
    public BizResult closeLoanOrder(final CloseLoanOrderForm closeLoanOrderForm) {
        BizResult bizResult = new BizResult();
        if (null == closeLoanOrderForm || null == closeLoanOrderForm.getId() || closeLoanOrderForm.getId() < 1L
                || StringUtil.isEmpty(closeLoanOrderForm.getReason())) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return bizResult;
        }
        try {
            LoanOrderQuery query = new LoanOrderQuery();
            LoanOrderQuery.Criteria criteria = query.createCriteria();
            criteria.andIdEqualTo(closeLoanOrderForm.getId());
            if (loanOrderManager.countByQuery(query) == 0) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
                return bizResult;
            }
            final LoanOrderDO loanOrderDO = new LoanOrderDO();
            loanOrderDO.setId(closeLoanOrderForm.getId());
            loanOrderDO.setStatus(LoanOrderStatusEnum.closed.getCode());
            if (loanOrderManager.updateByPrimaryKeySelective(loanOrderDO) == 1) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.SUCCESS);
                //增加操作日志
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        AdminUser adminUser = AdminUserUtil.getUser();
                        ActLogDO actLogDO = new ActLogDO();
                        actLogDO.setBizType(ActLogBizTypeEnum.LoanOrder.name());
                        actLogDO.setBizId(closeLoanOrderForm.getId());
                        actLogDO.setActorName(adminUser.getName());
                        actLogDO.setActorId(adminUser.getAdminId());
                        actLogDO.setActorLabel(adminUser.getDepartmentName());
                        actLogDO.setActDetail(closeLoanOrderForm.getReason());
                        actLogDO.setActTitle(ActLogActorNameEnum.close.name());
                        actLogManager.insertSelective(actLogDO);
                        userMsgAO.closeOrder(loanOrderManager.selectByPrimaryKey(loanOrderDO.getId()), closeLoanOrderForm.getReason());
                    }
                }).start();
            } else {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.UPDATE_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return bizResult;
    }

    @Override
    public BizResult deleteLoanOrder(final CloseLoanOrderForm closeLoanOrderForm) {
        BizResult bizResult = new BizResult();
        if (null == closeLoanOrderForm || null == closeLoanOrderForm.getId() || closeLoanOrderForm.getId() < 1L
                || StringUtil.isEmpty(closeLoanOrderForm.getReason())) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return bizResult;
        }
        try {
            LoanOrderQuery query = new LoanOrderQuery();
            LoanOrderQuery.Criteria criteria = query.createCriteria();
            criteria.andIdEqualTo(closeLoanOrderForm.getId());
            if (loanOrderManager.countByQuery(query) == 0) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
                return bizResult;
            }
            final LoanOrderDO loanOrderDO = new LoanOrderDO();
            loanOrderDO.setId(closeLoanOrderForm.getId());
            loanOrderDO.setIsDeleted(Boolean.TRUE);
            if (loanOrderManager.updateByPrimaryKeySelective(loanOrderDO) == 1) {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.SUCCESS);
                //增加操作日志
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        AdminUser adminUser = AdminUserUtil.getUser();
                        ActLogDO actLogDO = new ActLogDO();
                        actLogDO.setBizType(ActLogBizTypeEnum.LoanOrder.name());
                        actLogDO.setBizId(closeLoanOrderForm.getId());
                        actLogDO.setActorName(adminUser.getName());
                        actLogDO.setActorId(adminUser.getAdminId());
                        actLogDO.setActorLabel(adminUser.getDepartmentName());
                        actLogDO.setActDetail(closeLoanOrderForm.getReason());
                        actLogDO.setActTitle(ActLogActorNameEnum.deleteLoanOrder.name());
                        actLogManager.insertSelective(actLogDO);
                        //发送短信
//                      userMsgAO.closeOrder(loanOrderManager.selectByPrimaryKey(loanOrderDO.getId()), closeLoanOrderForm.getReason());
                    }
                }).start();
            } else {
                bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.UPDATE_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return bizResult;
    }

    @Override
    public BizResult queryLoanOrderActLogs(QueryLoanOrderActLogForm actLogForm) {
        BizResult bizResult = new BizResult();
        if (null == actLogForm || null == actLogForm.getId() || actLogForm.getId() < 1L) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.PARAM_ERROR);
            return bizResult;
        }
        try {
            ActLogQuery actLogQuery = new ActLogQuery();
            ActLogQuery.Criteria criteria = actLogQuery.createCriteria();
            criteria.andBizTypeEqualTo(ActLogBizTypeEnum.LoanOrder.name());
            criteria.andBizIdEqualTo(actLogForm.getId());
            actLogQuery.setPageNo(actLogForm.getPageNo());
            actLogQuery.setPageSize(actLogForm.getPageSize());
            actLogQuery.setOrderByClause("id desc");
            PageResult<ActLogDO> pageResult = actLogManager.selectByQueryWithPage(actLogQuery);
            bizResult.setResultDate(pageResult);
            bizResult.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return bizResult;
    }

    @Override
    public BizResult getContractInfo(Long id) {
        BizResult bizResult = new BizResult();
        List<ApplyForLoanVO> list = loanOrderAOFacade.getContractInfo(id);
        if (list == null || list.size() == 0) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
        } else {
            bizResult.setResultDate(list);
        }
        return bizResult;
    }

    @Override
    public BizResult getLetterInfo(Long id) {
        BizResult bizResult = new BizResult();
        LetterInfoVO letterInfoVO = loanOrderAOFacade.getLetterInfo(id);
        if (letterInfoVO == null) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
        } else {
            bizResult.setResultDate(letterInfoVO);
        }
        return bizResult;
    }

    @Override
    public BizResult createContractPDF(String path, Long id, HttpServletResponse response) {
        loanOrderAOFacade.createContractPDF(path, id, response);
        return null;
    }

    @Override
    public BizResult createContract(Long id) {
        BizResult bizResult = new BizResult();
        ContractVO letterInfoVO = loanOrderAOFacade.createContract(id);
        if (letterInfoVO == null) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.NO_DATA);
        } else {
            bizResult.setResultDate(letterInfoVO);
        }
        return bizResult;
    }

    @Override
    public BizResult checkSendLetter(Long id) {
        BizResult bizResult = new BizResult();
        Boolean result = loanOrderAOFacade.sendLetter(id);
        if (!result) {
            bizResult.setResultCodeAndMsg(BaseConstants.ResultCode.EXCEPTION);
        }
        return bizResult;
    }
}
